import { Button, Card, DatePicker, Flex, List, ListView, Toast, WhiteSpace, WingBlank } from "antd-mobile";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
// import { ROUTE_PATH } from "src/projects/app/util-tool";
import { request, setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import "./index.less";
// import { Row } from "antd";

/**
 * 组件：慈善信息汇总状态
 */
export interface CharitableInformationViewState extends ReactViewState {
    // 捐款列表
    donate_list?: any;
    // 捐款列表数量
    donate_list_count?: number;
    // 受助列表
    recipient_list?: any;
    // 受助列表数量
    recipient_list_count?: number;
    // 当前月份
    now_month?: any;
    now_showing_month?: any;
    now_month_obj?: any;
    // 收入总金额
    income_sum?: number;
    // 支出总金额
    output_sum?: number;
    // 总余额
    all_money_sum?: number;
    // 过审数量
    pass_sum?: number;
    // 捐赠数据源
    donateDataSource?: any;
    // 募捐数据源
    recipientDataSource?: any;
    // 是否发送
    isSend?: boolean;
}

const getDataBlob = (datas: any) => {
    const dataBlob = {};
    datas.map((item: any, index: number) => {
        dataBlob[`${index}`] = `row - ${index}`;
    });
    return dataBlob;
};

const ds = new ListView.DataSource({
    rowHasChanged: (row1: any, row2: any) => row1 !== row2,
});

/**
 * 组件：慈善信息汇总
 * 慈善信息汇总
 */
export class CharitableInformationView extends ReactView<CharitableInformationViewControl, CharitableInformationViewState> {

    public lv1: any = null;
    public lv2: any = null;

    constructor(props: any) {
        super(props);

        this.state = {
            donate_list: [],
            recipient_list: [],
            donate_list_count: 0,
            recipient_list_count: 0,
            now_month: '',
            now_showing_month: '',
            now_month_obj: new Date(Date.now()),
            pass_sum: 0,
            income_sum: 0,
            output_sum: 0,
            all_money_sum: 0,
            donateDataSource: ds,
            recipientDataSource: ds,
        };
    }
    // 月份变更
    changeMonth(e: any) {
        this.setState({
            now_month_obj: e,
            now_month: this.formatDate(e),
        });
    }
    componentDidMount() {
        let user = IntelligentElderlyCareAppStorage.getCurrentUser();
        if (!user) {
            this.props.history!.push(ROUTE_PATH.login);
            return;
        }
        this.getMonthData();
    }
    btnClick() {
        let { now_showing_month, now_month, isSend } = this.state;
        if (isSend) {
            Toast.fail('请勿操作过快！');
            return;
        }

        if (now_showing_month !== '' && now_showing_month === now_month) {
            return;
        }
        Toast.loading('查询中...', 11);
        setTimeout(
            () => {
                this.setState({
                    isSend: false,
                });
            },
            10000,
        );
        this.setState(
            {
                isSend: true,
            },
            () => {
                this.getMonthData();
            }
        );
    }
    getMonthData() {
        let { now_month, now_month_obj } = this.state;
        // 给个默认值
        now_month = now_month || this.formatDate(now_month_obj);
        let param: any = {
            month: now_month,
        };
        // 汇总信息
        request(this, AppServiceUtility.charitable_service.get_charitable_information_list_all!(param, 1, 10))
            .then((datas: any) => {

                Toast.hide();

                let donate_list = datas['donate_list'] && datas['donate_list']['result'] ? datas['donate_list']['result'] : [];

                const donateDataBlob = getDataBlob(donate_list);

                let income_sum = 0;

                donate_list.map((item: any, index: number) => {
                    income_sum += item['donate_money'];
                });

                let recipient_list = datas['recipient_list'] && datas['recipient_list']['result'] ? datas['recipient_list']['result'] : [];

                const recipientDataBlob = getDataBlob(recipient_list);

                let output_sum = 0;

                recipient_list.map((item: any, index: number) => {
                    output_sum += item['apply_money'];
                });

                this.setState({

                    pass_sum: datas['appropriation_list'] && datas['appropriation_list']['total'] ? datas['appropriation_list']['total'] : 0,
                    // 
                    donate_list_count: datas['donate_list'] && datas['donate_list']['total'] ? datas['donate_list']['total'] : 0,
                    // 
                    donate_list,
                    donateDataSource: this.state.donateDataSource.cloneWithRows(donateDataBlob),
                    // 
                    income_sum,

                    // 
                    recipient_list_count: datas['recipient_list'] && datas['recipient_list']['total'] ? datas['recipient_list']['total'] : 0,
                    // 
                    recipient_list,
                    recipientDataSource: this.state.recipientDataSource.cloneWithRows(recipientDataBlob),
                    //
                    output_sum,

                    // 
                    all_money_sum: income_sum - output_sum,

                    // 
                    now_month,
                    now_showing_month: now_month,
                    // 
                    isSend: false,
                });
            }).catch(error => {
                Toast.hide();
                this.setState(
                    {
                        isSend: false,
                    },
                    () => {
                        Toast.fail(error.message);
                    }
                );
            });
    }
    formatDate(date: any) {
        const pad = (n: any) => n < 10 ? `0${n}` : n;
        const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}`;
        return `${dateStr}`;
    }
    render() {
        setMainFormTitle("慈善信息汇总");
        const separator = (sectionID: any, rowID: any) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 8,
                    // borderTop: '1px solid #ECECED',
                    // borderBottom: '1px solid #ECECED',
                }}
            />
        );
        const { donate_list_count, recipient_list_count, donateDataSource, recipientDataSource, pass_sum, income_sum, output_sum, all_money_sum, donate_list, recipient_list, now_month_obj } = this.state;

        let index1 = donate_list.length - 1;
        const row1 = (rowData: any, sectionID: any, rowID: any) => {
            if (index1 < 0) {
                index1 = donate_list.length - 1;
            }
            const obj = donate_list[index1--];
            return (
                <div key={rowID} style={{ padding: '0 15px' }}>
                    <div style={{ display: 'flex', padding: '8px 0' }}>
                        <div>申请名字：{obj.donate_name}</div>
                    </div>
                    <div style={{ display: 'flex', padding: '8px 0' }}>
                        <div>申请金额：{obj.donate_money}</div>
                    </div>
                    <div style={{ display: 'flex', padding: '8px 0' }}>
                        <div>申请时间：{obj.create_date}</div>
                    </div>
                </div>
            );
        };
        let index2 = recipient_list.length - 1;
        const row2 = (rowData: any, sectionID: any, rowID: any) => {
            if (index2 < 0) {
                index2 = recipient_list.length - 1;
            }
            const obj = recipient_list[index2--];
            return (
                <div key={rowID} style={{ padding: '0 15px' }}>
                    <div style={{ display: 'flex', padding: '8px 0' }}>
                        <div>捐款人：{obj.apply_name}</div>
                    </div>
                    <div style={{ display: 'flex', padding: '8px 0' }}>
                        <div>捐款金额：{obj.apply_money}</div>
                    </div>
                    <div style={{ display: 'flex', padding: '8px 0' }}>
                        <div>捐款时间：{obj.create_date}</div>
                    </div>
                </div>
            );
        };
        return (
            <Card className="app-charitable-information">
                <WingBlank size="sm">
                    <DatePicker
                        mode="month"
                        title="选择月份"
                        extra="Optional"
                        value={now_month_obj}
                        onChange={(e) => this.changeMonth(e)}
                        format={val => `${this.formatDate(val)}`}
                    >
                        <List.Item arrow="horizontal">选择月份</List.Item>
                    </DatePicker>
                    <Button type="primary" onClick={() => this.btnClick()}>查询</Button>
                    <WhiteSpace size="xl" />
                    <div className="aci-title aci-title1">
                        <strong>当月信息汇总</strong>
                    </div>
                    <Flex justify="center">
                        <Flex.Item>
                            <div>当月捐款数量</div>
                            <div className="aci-num">{donate_list_count}</div>
                        </Flex.Item>
                        <Flex.Item>
                            <div>当月募捐数量</div>
                            <div className="aci-num">{recipient_list_count}</div>
                        </Flex.Item>
                        <Flex.Item>
                            <div>审批数量</div>
                            <div className="aci-num">{pass_sum}</div>
                        </Flex.Item>
                        <Flex.Item>
                            <div>收入总金额</div>
                            <div className="aci-num">{income_sum}</div>
                        </Flex.Item>
                        <Flex.Item>
                            <div>支出总金额</div>
                            <div className="aci-num">{output_sum}</div>
                        </Flex.Item>
                        <Flex.Item>
                            <div>当月总余额</div>
                            <div className="aci-num">{all_money_sum}</div>
                        </Flex.Item>
                    </Flex>
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="xs" />
                    <div className="aci-title aci-title1">
                        <strong>当月捐款信息</strong>
                    </div>
                    <WhiteSpace size="xs" />
                    {(() => {
                        if (donate_list.length > 0) {
                            return (
                                <ListView
                                    ref={el => this.lv1 = el}
                                    dataSource={donateDataSource}
                                    renderRow={row1}
                                    renderSeparator={separator}
                                    pageSize={4}
                                    useBodyScroll={true}
                                    scrollRenderAheadDistance={500}
                                />
                            );
                        } else {
                            return (
                                <div>
                                    <strong>暂无</strong>
                                </div>
                            );
                        }
                    })()}
                    <WhiteSpace size="xs" />
                    <div className="aci-title aci-title2">
                        <strong>当月募捐信息</strong>
                    </div>
                    <WhiteSpace size="xs" />
                    {(() => {
                        if (recipient_list.length > 0) {
                            return (
                                <ListView
                                    ref={el => this.lv2 = el}
                                    dataSource={recipientDataSource}
                                    renderRow={row2}
                                    renderSeparator={separator}
                                    pageSize={4}
                                    useBodyScroll={true}
                                    scrollRenderAheadDistance={500}
                                />
                            );
                        } else {
                            return (
                                <div>
                                    <strong>暂无</strong>
                                </div>
                            );
                        }
                    })()}
                </WingBlank>
            </Card>
        );
    }
}

/**
 * 控件：慈善信息汇总控制器
 * 慈善信息汇总
 */
@addon('CharitableInformationView', '慈善信息汇总', '慈善信息汇总')
@reactControl(CharitableInformationView, true)
export class CharitableInformationViewControl extends ReactViewControl {

}